import socket

# 创建一个TCP服务器套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#  将SO_REUSEADDR 设置为1，表示重复使用此端口，避免出现address already In use错误。
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# 将套接字的地址设置为127.0.0.1:8000
address = ("127.0.0.1", 8000)
server_socket.bind(address)
# 开启监听传入的连接
server_socket.listen()

"""
    多个客户端连接，第一个连接的客户端如何没发送消息，则会阻塞，其他客户端
    需要等第一个连接的客户端发送后，才能连接。
"""
try:

    connections = []
    while True:
        # 等待连接
        connection, client_address = server_socket.accept()
        print(f"从{client_address}获取一个连接")
        connections.append(connection)
        for connection in connections:
            buffer = b""
            while buffer[-2:] != b"\r\n":
                data = connection.recv(2)
                if not data:
                    break
                else:
                    print(f"获取数据：{data}")
                    buffer += data
            connection.sendall(buffer)
finally:
    server_socket.close()
